(function () {
    var init = function () {
        initEvents();
    }

    var initEvents = function () {
        send.addEventListener('click', onSendClick)
        mainContainer.addEventListener('scroll', onScroll)
    }
    var onScroll = function () {
        // console.log(this.scrollTop)
        // console.log(this.scrollTop)
        // this.scrollTop = this.scrollTop mainContainer.offsetHeight

    }

    var onSendClick = function () {
        var txt = input.value.trim();
        if (!txt) return
        renderSelfSendChat(txt)
        var selfHeight = mainContainer.offsetHeight
        mainContainer.scrollTo(0, selfHeight)
    }

    var renderSelfSendChat = function (txt) {
        renderText(txt, 'right')
        input.value = ''
        //自己消息发送出去之后，现在需要去请求机器人回消息
        renderRobotText(txt)
    }

    var renderRobotText = function (txt) {
        ajax({
            url: 'https://api.hyfarsight.com/test/testRequest/robotChat',
            method: 'POST',
            data: {
                txt: txt
            },
            onSuccess: function (res) {
                renderText(res.responseTxt, 'left')
                mainContainer.scrollTo(0, mainContainer.offsetHeight)
            }
        })
    }

    var renderText = function (txt, direction) {
        var divParent = document.createElement('div')
        divParent.className = direction === 'right' ? 'chat-container avatar-chat' : 'chat-container robot-chat';
        var img = new Image();
        img.src = direction === 'right' ? './img/avatar.jpg' : './img/robot.jpg';
        var divTxt = document.createElement('div')
        divTxt.className = 'chat-txt'
        divTxt.innerHTML = txt.replace(/{br}/g, '<br/>');
        divParent.appendChild(img)
        divParent.appendChild(divTxt)
        document.querySelector('.main').appendChild(divParent)
        var robotHeight = divParent.offsetHeight
    }

    init()
})()